package com.iot.ammeter.service.impl.web.setting;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iot.ammeter.constant.Constant;
import com.iot.ammeter.entity.web.setting.Setting;
import com.iot.ammeter.mapper.web.setting.SettingMapper;
import com.iot.ammeter.service.web.setting.SettingService;
import com.iot.ammeter.utils.SnowFlakeIdWorker;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author basil
 * @since 2022-03-10
 */
@Service
public class SettingServiceImpl extends ServiceImpl<SettingMapper, Setting> implements SettingService {

    private final SettingMapper settingMapper;
    private final SnowFlakeIdWorker snowFlakeIdWorker;

    public SettingServiceImpl(SettingMapper settingMapper, SnowFlakeIdWorker snowFlakeIdWorker) {
        this.settingMapper = settingMapper;
        this.snowFlakeIdWorker = snowFlakeIdWorker;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean setElectricityPrices(String price) {
        Setting setting = settingMapper.selectOne(new LambdaQueryWrapper<Setting>().eq(Setting::getSettingKey, Constant.Setting.ELECTRICITY_PRICES));
        if (setting == null) {
            setting = new Setting();
            setting.setSettingId(String.valueOf(snowFlakeIdWorker.nextId()));
            setting.setSettingKey(Constant.Setting.ELECTRICITY_PRICES);
            setting.setSettingValue(price);
            setting.setCreateTime(LocalDateTime.now());
        }
        setting.setSettingValue(price);
        setting.setUpdateTime(LocalDateTime.now());
        return this.saveOrUpdate(setting);
    }
}
